package com.vlong.town.util.data;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数据处理工具类
 * @author Assassin
 */
public final class DataUtil {

	// Fields

	/**
	 * 生成MD5密文
	 * @param source 明文byte数组
	 * @return 密文
	 */
	public static String generateMD5(byte[] source) {
		String result = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest();
			char str[] = new char[16 * 2];
			int k = 0;
			for (int i = 0; i < 16; i++) {
				byte byte0 = tmp[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			result = new String(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 生成随机密码
	 * @param length 密码长度
	 * @return String 密码明文
	 */
	public static String generatePassword(int length) {
		String val = "";
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			String charOrNum = random.nextInt(2) % 2 == 0 ? "num" : "num";
			if ("char".equalsIgnoreCase(charOrNum)) {
				int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
				val += (char) (choice + random.nextInt(26));
			} else if ("num".equalsIgnoreCase(charOrNum)) {
				val += String.valueOf(random.nextInt(10));
			}
		}
		return val;
	}

	/**
	 * 生成用户登录Token
	 * @param userId 用户Id
	 * @return token 登录Token[userId + UUID]
	 */
	public static String generateIdentificationCode(String userId) {
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		return userId + uuid;
	}

	/**
	 * IP地址字符串转换为long型数据
	 * @param ip IP地址字符串
	 * @return long long型数据
	 */
	public static long ip2long(String ip) {
		long result = 0L;
		try {
			String[] ip_strings = ip.split("\\.");
			if (ip_strings.length != 4) {
				throw new Exception("输入IP地址格式不正确");
			}
			int[] ip_ints = new int[4];
			for (int i = 0; i < 4; i++) {
				ip_ints[i] = Integer.parseInt(ip_strings[i]);
			}
			for (int i = 0; i < 4; i++) {
				result += ip_ints[i] * Math.pow(256, 3 - i);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * long型数据IP地址转换为字符串型IP地址
	 * @param ip 型数据IP地址
	 * @return String IP地址字符串
	 */
	public static String long2ip(long ip) {
		String result = "";
		result += ip % 256;
		ip /= 256;
		result = ip % 256 + "." + result;
		ip /= 256;
		result = ip % 256 + "." + result;
		ip /= 256;
		result = ip % 256 + "." + result;
		return result;
	}

	/**
	 * 格式化输出实体
	 * @param entity  实体对象
	 * @return 格式化字符串
	 */
	public static String formatEntity(Object entity) {
		String entityFormat = "";
		Class<? extends Object> cls = entity.getClass();
		Field[] fields = cls.getDeclaredFields();
		for (Field field : fields) {
			if (field.getName().equals("serialVersionUID")) {
				continue;
			}
			char[] buffer = field.getName().toCharArray();
			buffer[0] = Character.toUpperCase(buffer[0]);
			String mothodName = "get" + new String(buffer);
			try {
				Method method = cls.getDeclaredMethod(mothodName);
				Object resutl = method.invoke(entity);
				entityFormat += "\n" + field.getName() + "=>" + resutl;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return entityFormat;
	}
	
	/**
	 * 是否为空（包括：Null和Trim后的空串）
	 * @param input 输入字符串
	 * @return true-为空 | false-不为空
	 */
	public static boolean isEmpty(String input) {
		if(input == null || "".equals(input.trim())) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 是否为空串（单一空串，未Trim）
	 * @param input 输入字符串
	 * @return true-为空串 | false-不为空串
	 */
	public static boolean isBlank(String input) {
		if(input != null && "".equals(input)) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 是否为空串（多个空串，已Trim）
	 * @param input 输入字符串
	 * @return true-为空串 | false-不为空串
	 */
	public static boolean isTrimBlank(String input) {
		if(input != null && "".equals(input.trim())) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 验证字符串长度
	 * @param input 输入字符串
	 * @param minLength 验证长度-最小长度
	 * @param maxLength 验证长度-最大长度
	 * @return true-长度合法 | false-长度不合法
	 */
	public static boolean validateLength(String input, int minLength, int maxLength) {
		if(input.length() <= maxLength && input.length() >= minLength) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除Html标签元素
	 * @param htmlStr
	 * @param  length
	 * @return result
	 */
	public static String delHTMLTag(String htmlStr, int length) {

		final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
		final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
		final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
		final String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符
		final String regEx_nbsp = "&nbsp;";//定义空格回车换行符

		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签
		
		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签

		Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
		Matcher m_space = p_space.matcher(htmlStr);
		htmlStr = m_space.replaceAll(""); // 过滤回车标签
		htmlStr = htmlStr.replaceAll(" ", "");
		
		Pattern p_nbsp = Pattern.compile(regEx_nbsp, Pattern.CASE_INSENSITIVE);
		Matcher m_nbsp = p_nbsp.matcher(htmlStr);
		htmlStr = m_nbsp.replaceAll(""); // 过滤空格标签
		
		htmlStr = htmlStr.trim();

		if(length > 0) {
			if(htmlStr.length() > length) {
				htmlStr = htmlStr.substring(0, length) + "......";
			}
		}

		return htmlStr;
	}

}